/**
 * 维护http状态码和http请求工具和相关业务逻辑
 */
import Vue from 'vue'
import axios from 'axios'
import {
  EVENT_USER_INFO,
  HTTP_CODE_NETWORK_ERROR,
  HTTP_CODE_SESSION_INVALID
} from 'constants/'
import { downloadFile } from 'utils'
import { getToken } from 'app/global'
import { toAppResult } from 'app/converter'
import i18n from '@/i18n/'
import router from '@/router'

// http api 根目录
const API_URL = '/api'

// 创建axios实例
const service = axios.create({
  baseURL:
    process.env.NODE_ENV === 'production' ? process.env.VUE_APP_HTTP_API : '/', // api 的 base_url
  timeout: 600000 // 请求超时时间
})

// request 拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers.Authorization = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    // Promise.reject(error)
  }
)

// response 拦截器
// service.interceptors.response.use(
//   response => {
//     console.log('response')
//     const res = response.data
//     return res
//   },
//   error => {
//     console.log('error')
//     return Promise.reject(error)
//   }
// )

// 向服务器端发送 http 请求
export function request({
  url,
  method,
  params,
  data,
  responseType,
  responseFileType,
  showLoading,
  showMsg,
  showErr
}) {
  return new Promise((resolve, reject) => {
    let loading
    if (showLoading) {
      loading = Vue.prototype.$loading({
        lock: true
        // text: '系统拼命加载中...'
        // spinner: 'el-icon-loading'
        // background: 'rgba(0, 0, 0, 0.7)'
      })
    }
    service({
      url: API_URL + url,
      method,
      params,
      data,
      responseType
    }).then(
      res => {
        loading && loading.close()
        if (responseType === 'blob') {
          downloadFile(res.data, responseFileType)
        } else {
          const data = toAppResult(res.data)
          showMsg && data.msg && Vue.prototype.$success(data.msg)
          resolve(data)
        }
      },
      err => {
        loading && loading.close()
        const data = toAppResult(err.response.data)
        if (data.code === HTTP_CODE_SESSION_INVALID) {
          Vue.prototype.$bus.$emit(EVENT_USER_INFO, null)
          router.push('/login')
        }
        const code = data.code || HTTP_CODE_NETWORK_ERROR
        const msg = data.msg || i18n.t('tip.networkError')
        if (showMsg || showErr) {
          Vue.prototype.$error(msg)
        }
        reject({ code, msg })
      }
    )
  })
}
